package com.bsoft.wx.config.shiro;

import com.auth0.jwt.exceptions.TokenExpiredException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @program: emos-wx-api
 * @description: 全局过滤器类
 * @author: hdh
 * @create: 2023:02:02 10:57
 */
 /*
 因为在 OAuth2Filter 类中要读写 ThreadLocal 中的数据，所以 OAuth2Filter 类必
须要设置成多例的，否则 ThreadLocal 将无法使用。


  */
@Component
@Scope("prototype")  //多例
public class OAuth2Filter extends AuthenticatingFilter {
    @Autowired
    private ThreadLocalToken threadLocalToken;
    @Value("${emos.jwt.cahe-expire}")
    private int cacheExpire;
    @Autowired
    private JwtUtil jwtUtil;  //调用有限性

    @Autowired
    private RedisTemplate redisTemplate;

    //获取请求头的token
    private String getRequestToken(HttpServletRequest httpRequest) {
        //从head 获取token
        String token = httpRequest.getHeader("token");
        //如果header 中不存在 则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = httpRequest.getParameter("token");
        }
        return token;
    }

    /*
      请求拦截之后 用于把令牌字符串封装成令牌对象
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = getRequestToken(req);
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return new OAuth2Token(token);
    }

    /*
     拦击请求 判断请求是否需要被shiro 处理
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest req = (HttpServletRequest) request;
        //ajax 提交applition/json 数据的时候 会先发Options 请求
        //这里放行Options请求 不需要Shiro 处理
        if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }
        //除了Options请求之外 所有的请求都要被Shiro 处理
        return false;
    }

    //该方法用于处理所有应该被shiro处理的请求
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-Type", "text/html;charset=UTF-8");
        //允许跨域请求
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        threadLocalToken.clear();
        //获取请求token 如果token不存在 直接返回401
        String token = getRequestToken(req);
        if (StringUtils.isBlank(token)) {
            resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
            resp.getWriter().println("无效的令牌");
            return false;
        }
        try {
            //检查令牌是否过期
            jwtUtil.verifierToken(token);
        } catch (TokenExpiredException e) {
            //客户端令牌过期 查询redis 中是否存在令牌 如果存在令牌 就重新生成一个新的令牌给客户端
            if (redisTemplate.hasKey(token)) {
                //删除令牌
                redisTemplate.delete(token);
                int userId = jwtUtil.getUserId(token);
                //生成新的token
                token = jwtUtil.createToken(userId);
                //把新的令牌保存到redis中
                redisTemplate.opsForValue().set(token, userId + "", cacheExpire, TimeUnit.DAYS);
                //把令牌绑定到线程
                threadLocalToken.setToken(token);
            } else {
                //如果redis 不存在令牌 让用户重新登录
                resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
                resp.getWriter().println("令牌已经过期");
                return false;

            }
        } catch (Exception e) {
            resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
            resp.getWriter().println("无效的令牌");
            return false;
        }
        boolean bool = executeLogin(req, resp);
        return bool;

    }

    //登录失败
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        try {
            resp.getWriter().print(e.getMessage());
        } catch (IOException exception) {

        }
        return false;
    }

    @Override
    public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        super.doFilterInternal(request, response, chain);
    }
}
